package com.xlf.util;

import java.lang.reflect.Field;

import org.apache.commons.beanutils.BeanUtils;

import com.jfinal.plugin.activerecord.Model;
import com.sun.org.apache.bcel.internal.generic.Type;
import com.xlf.web.SessionCatalog;

public class ModelCopier {
	
	public static final String TYPE_STRING = "class java.lang.String";
	public static final String TYPE_INT = "int";
	public static final String TYPE_FLOAT = "float";
	public static final String TYPE_DOUBLE = "double";
	
	public static void copyModelToBean(Model model, Object bean) {
		try {
			Field[] fields = bean.getClass().getDeclaredFields();
			for(Field field : fields) {
				// 仅处理基本类型
				if(field.getGenericType().toString().equals(ModelCopier.TYPE_STRING) || 
						field.getGenericType().toString().equals(ModelCopier.TYPE_INT) ||
						field.getGenericType().toString().equals(ModelCopier.TYPE_FLOAT) ||
						field.getGenericType().toString().equals(ModelCopier.TYPE_DOUBLE)) {
					String fName = field.getName();
					BeanUtils.setProperty(bean, fName, model.get(fName));
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public static void copyBeanToModel(Object bean, Model model) {
		try {
			Field[] fields = bean.getClass().getDeclaredFields();
			for(Field field : fields) {
				String fName = field.getName();
				if(model.get(fName) != null) {
					// model中已具备值，不要被新的null给冲掉
					continue;
				}
				String value = BeanUtils.getProperty(bean, fName);
				
				// 仅处理基本类型
				if(field.getGenericType().toString().equals(ModelCopier.TYPE_STRING) && value != null) {
					model.set(fName, value);
				} else if(field.getGenericType().toString().equals(ModelCopier.TYPE_INT)) {
					model.set(fName, Integer.parseInt(value));
				} else if(field.getGenericType().toString().equals(ModelCopier.TYPE_FLOAT)) {
					model.set(fName, Float.parseFloat(value));
				} else if(field.getGenericType().toString().equals(ModelCopier.TYPE_DOUBLE)) {
					model.set(fName, Double.parseDouble(value));
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		Field[] fs = SessionCatalog.class.getDeclaredFields();
		for(int i = 0; i < fs.length; i++) {
			System.out.println(fs[i].getName() + "-" + fs[i].getGenericType());
		}
	}

}
